package com.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;


/*
 * 杨成龙
 * redis 缓存初始化与管理
 * 
 * */


@Configuration
@EnableCaching  //注解驱动的缓存管理功能,会触发一个post processor，这会扫描每一个spring bean，查看是否已经存在注解对应的缓存。如果找到了，就会自动创建一个代理拦截方法调用，使用缓存的bean执行处理
public class RedisConfig {

    
    //jedisConnectionFactory获取Jedis实例
	@Bean
    JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        //连接redis及配置
        template.setConnectionFactory(jedisConnectionFactory());
        //设置序列化Key的实例化对象
        template.setKeySerializer(new GenericJackson2JsonRedisSerializer());
        //设置序列化Value的实例化对象
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        //初始化RedisTemplate
        template.afterPropertiesSet();
        return template;
    }
    
    @Bean//自定义缓存管理器
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate(factory));
        // Number of seconds before expiration. Defaults to unlimited (0)
        cacheManager.setDefaultExpiration(2592000); //设置key-value超时时间
        return cacheManager;
    }
    
}
